import { Effect, Reducer } from 'umi';

export type ShopingCartGoods = {
  name: string;
  price: number;
  num: number;
  gid: number | string;
  gimg: string;
  barcode: any;
  changeunitname: any;
  unit: any;
  categoryid: any;
};

export type ShopingCartState = {
  totalPrice: number;
  totalNum: number;
  goodsList: ShopingCartGoods[];
};

type ShopingCartModalType = {
  namespace: string;
  state: ShopingCartState;
  effects?: {};
  reducers?: {
    plus: Reducer<ShopingCartState>;
    reduce: Reducer<ShopingCartState>;
    cleanShopingCart: Reducer<ShopingCartState>;
  };
};

const Model: ShopingCartModalType = {
  namespace: 'shopingcart',
  state: {
    goodsList: [],
    totalNum: 0,
    totalPrice: 0,
  },
  effects: {},
  reducers: {
    plus(state, action) {
      let f = false;
      let totalPrice: number = JSON.parse(JSON.stringify(state?.totalPrice));
      let totalNum: number = JSON.parse(JSON.stringify(state?.totalNum));

      state?.goodsList.forEach((item) => {
        if (item.gid === action.data.gid) {
          item.num += 1;
          totalPrice += item.price;
          f = true;
        }
      });

      if (!f) {
        totalPrice += action.data.price;
        action.data.num += 1;
      }

      totalNum += 1;

      return {
        ...state,
        goodsList: f ? state?.goodsList : state?.goodsList.concat(action.data),
        totalPrice: totalPrice,
        totalNum: totalNum,
      };
    },
    reduce(state, action) {
      console.log(action.data);

      let totalPrice: number = JSON.parse(JSON.stringify(state?.totalPrice));
      let totalNum: number = JSON.parse(JSON.stringify(state?.totalNum));

      let index = -1;
      state?.goodsList.forEach((item, i) => {
        if (item.gid === action.data.gid) {
          item.num -= 1;
          totalPrice -= item.price;
          index = i;
        }
      });

      totalNum -= 1;

      if (action.data.num - 1 === 0 && index >= 0) {
        state?.goodsList.splice(index, 1);
      }
      return {
        ...state,
        totalNum,
        totalPrice,
        goodsList: state?.goodsList,
      };
    },
    cleanShopingCart(state, action) {
      return {
        ...state,
        ...action.data,
      };
    },
  },
};

export default Model;
